package com.ty.zls.activity;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.qmuiteam.qmui.util.QMUIDisplayHelper;
import com.qmuiteam.qmui.util.QMUIStatusBarHelper;
import com.qmuiteam.qmui.util.QMUIViewHelper;
import com.qmuiteam.qmui.widget.QMUIEmptyView;
import com.qmuiteam.qmui.widget.QMUITopBarLayout;
import com.qmuiteam.qmui.widget.dialog.QMUIBottomSheet;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;
import com.qmuiteam.qmui.widget.grouplist.QMUICommonListItemView;
import com.qmuiteam.qmui.widget.grouplist.QMUIGroupListView;
import com.qmuiteam.qmui.widget.roundwidget.QMUIRoundButton;
import com.ty.zls.R;
import com.ty.zls.bean.Constants;
import com.ty.zls.bean.PrintWater;
import com.ty.zls.bean.Water;
import com.ty.zls.components.ImageAttachView;
import com.ty.zls.task.BaseTask;
import com.ty.zls.task.WaterTask;
import com.ty.zls.util.CommonUtil;
import com.ty.zls.util.HttpUtil;
import com.ty.zls.util.LocationUtil;
import com.ty.zls.util.StringUtils;
import com.ty.zls.util.StrogeUtil;
import com.ty.zls.widget.MyConfirrmDialog;
import com.xuexiang.xaop.annotation.Permission;
import com.xuexiang.xaop.consts.PermissionConsts;

import org.json.JSONArray;
import org.json.JSONObject;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 抄表activity
 */
public class WaterActivity extends AppCompatActivity implements View.OnClickListener {


    @ViewInject(R.id.qg_water_add_list)
    private QMUIGroupListView qg_water_add_list;

    @ViewInject(R.id.water_topbar)
    private QMUITopBarLayout water_topbar;

    @ViewInject(R.id.bt_water_add_sub)
    private Button bt_water_add_sub;

    @ViewInject(R.id.qe_water_add)
    private QMUIEmptyView qe_water_add;
    QMUICommonListItemView userId;
    QMUICommonListItemView name;
    QMUICommonListItemView tel;
    QMUICommonListItemView area;
    QMUICommonListItemView lastTime;
    QMUICommonListItemView sort;
    QMUICommonListItemView presort;
    QMUICommonListItemView scale;
    QMUICommonListItemView feedBack;
    QMUICommonListItemView attach;
    private Integer choiceBack;
    QMUIRoundButton feedbacktbtn;
    ImageAttachView attachView;
    QMUIRoundButton presortbtn;
    QMUIRoundButton editSort;
    EditText editScale;
    Water water;

    Map<String, String> map = new HashMap<>();
    private Map<String, Integer> feedBacks = new HashMap<>();
    private String[] feedBackArray;
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    //抄表 跳转标志
    boolean waterFlag = false;
    // 上一份 下一份标志
    boolean stepFlag = false;
    BaseTask baseTask;
    private QMUICommonListItemView last_scale;
    private String mLat = "";
    private String mLng = "";
    private boolean isGetLocation = false;
    private boolean isClickUpload = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        QMUIStatusBarHelper.translucent(this);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_water);
        x.view().inject(this);
        initLocation();
        initPager();
        initTopBar();
    }

    /**
     * 初始化topbar
     */
    private void initTopBar() {
        water_topbar.setBackgroundColor(getResources().getColor(R.color.app_color_theme_7));
        water_topbar.setTitle("抄表");
        water_topbar.addLeftBackImageButton().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                WaterActivity.this.finish();
            }
        });
        water_topbar.addLeftTextButton("上一个", QMUIViewHelper.generateViewId()).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (water == null) {
                    Toast.makeText(WaterActivity.this, "暂无抄表数据", Toast.LENGTH_SHORT).show();
                    return;
                }
                stepFlag = true;
                baseTask = new BaseTask(HttpUtil.PREV_WATER, WaterActivity.this, nextcallback);
                map.put("accountId", String.valueOf(userId.getDetailText()));
                baseTask.execute(map);
            }
        });
        water_topbar.addRightTextButton("下一个", QMUIViewHelper.generateViewId()).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                waterFlag = false;
                stepFlag = false;
                next();
            }
        });
    }

    /**
     * 加载进入数据
     */
    private void initData() {
        // 用户编号
        String id = getIntent().getStringExtra("id");
        baseTask = new BaseTask(HttpUtil.WATER_ADD, WaterActivity.this, callback);
        map.put("accountId", id);
        baseTask.setFailCallback(failCallback);
        baseTask.execute(map);
    }

    /**
     * 显示数据
     */
    private void initPager() {
        createGroup();
        initData();
        bt_water_add_sub.setOnClickListener(this);
    }


    /**
     * 设置抄表用户信息
     */
    public void setAccount(Water water) {
        userId.setDetailText(water.getId());
        name.setDetailText(water.getName());
        tel.setDetailText(water.getTel());
        area.setDetailText(water.getArea());
        lastTime.setDetailText(water.getLastTime());
        sort.setDetailText(water.getSort());
        last_scale.setDetailText(water.getLastScale());
        if (StringUtils.isEmpty(water.getPresort()) || "0".equals(water.getPresort())) {
            presortbtn.setText("置后");
        } else {
            presortbtn.setText("取消置后");
        }
        if (water.getCheck() == null || water.getCheck() == 0) {
            bt_water_add_sub.setText("提交");
            bt_water_add_sub.setClickable(true);
        } else {
            bt_water_add_sub.setText("该用户上期抄表正在审核");
            bt_water_add_sub.setClickable(false);
        }
        editScale.setText("");
        checkedIndex = 0;
        choiceBack = null;
        feedbacktbtn.setText("选择反馈类型");
        bitmap = null;
        attachView.hideImage();
    }


    /**
     * 选择feedback
     */
    int checkedIndex = 0;

    private void feedBack() {
        new QMUIDialog.CheckableDialogBuilder(this)
                .setCheckedIndex(checkedIndex)
                .addItems(feedBackArray, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (which == 0) {
                            feedbacktbtn.setText("选择反馈类型");
                            choiceBack = null;
                        } else {
                            feedbacktbtn.setText(feedBackArray[which]);
                            choiceBack = feedBacks.get(feedBackArray[which]);
                        }
                        checkedIndex = which;
                        dialog.dismiss();
                    }
                })
                .create(com.qmuiteam.qmui.R.style.QMUI_Dialog).show();
    }


    /**
     * 创建group
     */
    private void createGroup() {
        userId = qg_water_add_list.createItemView(
                ContextCompat.getDrawable(this, R.mipmap.user_id),
                "用户编号",
                null,
                QMUICommonListItemView.HORIZONTAL,
                QMUICommonListItemView.ACCESSORY_TYPE_NONE
        );

        name = qg_water_add_list.createItemView(
                ContextCompat.getDrawable(this, R.mipmap.user),
                "用户名",
                null,
                QMUICommonListItemView.HORIZONTAL,
                QMUICommonListItemView.ACCESSORY_TYPE_NONE
        );

        tel = qg_water_add_list.createItemView(
                ContextCompat.getDrawable(this, R.mipmap.tel),
                "手机号",
                null,
                QMUICommonListItemView.HORIZONTAL,
                QMUICommonListItemView.ACCESSORY_TYPE_CUSTOM
        );
        ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        QMUIRoundButton editTel = new QMUIRoundButton(this);
        editTel.setText("修改");
        editTelbtnId = QMUIViewHelper.generateViewId();
        editTel.setId(editTelbtnId);
        editTel.setLayoutParams(params);
        editTel.setTextColor(this.getResources().getColor(R.color.app_color_theme_5));
        editTel.setClickable(true);
        editTel.setOnClickListener(this);
        int padding = QMUIDisplayHelper.dp2px(this, 10);
        editTel.setPadding(padding, padding, padding, padding);
        tel.addAccessoryCustomView(editTel);

        area = qg_water_add_list.createItemView(
                ContextCompat.getDrawable(this, R.mipmap.address),
                "用水地址",
                null,
                QMUICommonListItemView.HORIZONTAL,
                QMUICommonListItemView.ACCESSORY_TYPE_NONE
        );

        lastTime = qg_water_add_list.createItemView(
                ContextCompat.getDrawable(this, R.mipmap.lasttime),
                "上期日期",
                null,
                QMUICommonListItemView.HORIZONTAL,
                QMUICommonListItemView.ACCESSORY_TYPE_NONE
        );


        sort = qg_water_add_list.createItemView(
                ContextCompat.getDrawable(this, R.mipmap.sort),
                "排序号",
                null,
                QMUICommonListItemView.HORIZONTAL,
                QMUICommonListItemView.ACCESSORY_TYPE_CUSTOM
        );
        editSort = new QMUIRoundButton(this);
        editSort.setText("修改");
        ViewGroup.LayoutParams params1 = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        editSort.setTextColor(this.getResources().getColor(R.color.app_color_theme_5));
        editSort.setLayoutParams(params1);
        editSort.setClickable(true);
        sortbtnId = QMUIViewHelper.generateViewId();
        editSort.setId(sortbtnId);
        editSort.setOnClickListener(this);
        editSort.setPadding(padding, padding, padding, padding);
        sort.addAccessoryCustomView(editSort);

        presort = qg_water_add_list.createItemView(
                ContextCompat.getDrawable(this, R.mipmap.presort),
                "置后排序",
                null,
                QMUICommonListItemView.HORIZONTAL,
                QMUICommonListItemView.ACCESSORY_TYPE_CUSTOM
        );
        presortbtn = new QMUIRoundButton(this);
        ViewGroup.LayoutParams params2 = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        presortbtn.setText("修改");
        presortbtn.setTextColor(this.getResources().getColor(R.color.app_color_theme_5));
        presortbtn.setLayoutParams(params2);
        presortbtn.setClickable(true);
        presortbtnId = QMUIViewHelper.generateViewId();
        presortbtn.setOnClickListener(this);
        presortbtn.setId(presortbtnId);
        presortbtn.setPadding(padding, padding, padding, padding);
        presort.addAccessoryCustomView(presortbtn);

        last_scale = qg_water_add_list.createItemView(
                ContextCompat.getDrawable(this, R.mipmap.scale),
                "上期指数",
                null,
                QMUICommonListItemView.HORIZONTAL,
                QMUICommonListItemView.ACCESSORY_TYPE_CUSTOM
        );

        scale = qg_water_add_list.createItemView(
                ContextCompat.getDrawable(this, R.mipmap.scale),
                "本期指数",
                null,
                QMUICommonListItemView.HORIZONTAL,
                QMUICommonListItemView.ACCESSORY_TYPE_CUSTOM
        );
        editScale = new EditText(this);
        ViewGroup.LayoutParams params3 = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        editScale.setLayoutParams(params3);
        editScale.setEms(10);
        editScale.setInputType(EditorInfo.TYPE_CLASS_NUMBER);
        scale.addAccessoryCustomView(editScale);

        feedBack = qg_water_add_list.createItemView(
                ContextCompat.getDrawable(this, R.mipmap.feedback),
                "抄表反馈",
                null,
                QMUICommonListItemView.HORIZONTAL,
                QMUICommonListItemView.ACCESSORY_TYPE_CUSTOM
        );
        feedbacktbtn = new QMUIRoundButton(this);
        feedbacktbtn.setText("选择反馈类型");
        feedbacktbtn.setLayoutParams(params3);
        feedbacktbtn.setClickable(true);
        feedbacktbtnId = QMUIViewHelper.generateViewId();
        feedbacktbtn.setId(feedbacktbtnId);
        feedbacktbtn.setOnClickListener(this);
        feedBack.addAccessoryCustomView(feedbacktbtn);

        attach = qg_water_add_list.createItemView(
                ContextCompat.getDrawable(this, R.mipmap.attch),
                "附件",
                null,
                QMUICommonListItemView.HORIZONTAL,
                QMUICommonListItemView.ACCESSORY_TYPE_CUSTOM
        );
        attach.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, QMUIDisplayHelper.dp2px(this, 110)));
        attachView = new ImageAttachView(this);
        attachView.setLayoutParams(new ViewGroup.LayoutParams(QMUIDisplayHelper.dp2px(this, 110), QMUIDisplayHelper.dp2px(this, 100)));
        attach.addAccessoryCustomView(attachView);
        attachView.setImageListener(this);

        int size = QMUIDisplayHelper.dp2px(this, 20);
        QMUIGroupListView.newSection(this)
                .setTitle("用户信息")
                .setLeftIconSize(size, ViewGroup.LayoutParams.WRAP_CONTENT)
                .addItemView(userId, null)
                .addItemView(name, null)
                .addItemView(tel, null)
                .addItemView(area, null)
                .addItemView(lastTime, null)
                .addItemView(sort, null)
                .addItemView(presort, null)
                .addItemView(last_scale, null)
                .addTo(qg_water_add_list);

        QMUIGroupListView.newSection(this)
                .setTitle("抄表信息")
                .setLeftIconSize(size, ViewGroup.LayoutParams.WRAP_CONTENT)
                .addItemView(scale, null)
                .addItemView(feedBack, null)
                .addItemView(attach, null)
                .addTo(qg_water_add_list);

    }

    int feedbacktbtnId;
    int presortbtnId;
    int sortbtnId;
    int editTelbtnId;

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == feedbacktbtnId) {
            //反馈
            feedBack();
        } else if (id == presortbtnId) {
            // 置后
            editPreSort();
        } else if (id == sortbtnId) {
            //排序
            editSort();
        } else if (id == editTelbtnId) {
            // 手机号
            editTel();
        } else if (id == R.id.bt_water_add_sub) {
            submit();
        } else if (id == R.id.qrb_add_attach) {
            // 附件添加
            shwoSheet();
        } else if (id == R.id.qrb_close_attach) {
            attachView.hideImage();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[]
            grantResults) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                if (0 == requestCode) {
                    Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                    startActivityForResult(intent, 0);
                } else if (requestCode == 1) {
                    Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    startActivityForResult(intent, 1);
                }
            } else {
                Toast.makeText(this, "请在设置中打开权限后继续", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent();
                intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                Uri uri = Uri.fromParts("package", getPackageName(), null);
                intent.setData(uri);
                startActivityForResult(intent, 0);
            }
        }
    }

    @Permission({PermissionConsts.CAMERA, PermissionConsts.STORAGE})
    private void shwoSheet() {
        new QMUIBottomSheet.BottomListSheetBuilder(this)
                .addItem("拍摄照片")
                .addItem("本地相册")
                .addItem("取消")
                .setOnSheetItemClickListener(new QMUIBottomSheet.BottomListSheetBuilder.OnSheetItemClickListener() {
                    @Override
                    public void onClick(QMUIBottomSheet dialog, View itemView, int position, String tag) {
                        if (position == 2) {
                            dialog.dismiss();
                        } else if (position == 0) {
                            if (CommonUtil.checkPermission(WaterActivity.this, new String[]{Manifest.permission.CAMERA}, 0)) {
                                Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                                startActivityForResult(intent, 0);
                            }
                        } else if (position == 1) {
                            if (CommonUtil.checkPermission(WaterActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1)) {
                                Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                                startActivityForResult(intent, 1);
                            }
                        }
                    }
                })
                .build()
                .show();
    }

    private Bitmap bitmap;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Bitmap temp = null;
        switch (requestCode) {
            // 照相机拍照
            case 0:
                if (resultCode == RESULT_OK) {
                    Bundle bundle = data.getExtras();
                    temp = (Bitmap) bundle.get("data");
                }
                break;
            // 图片库的图片
            case 1:
                if (resultCode == RESULT_OK) {
                    Uri uri = data.getData();
                    try {
                        temp = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                break;
            case 2:
                if (resultCode == RESULT_OK) {
                    submit();
                }
        }
        if (temp != null) {
            attachView.setImage(temp);
            attachView.showImage();
            this.bitmap = temp;
        }

    }


    private Water temp = null;

    /**
     * 提交
     */
    private void submit() {
        isClickUpload = true;
        if (TextUtils.isEmpty(mLat) || TextUtils.isEmpty(mLng)) {
            initLocation();
        } else {
            upload();
        }
    }

    private void upload() {
        final Integer scale = Integer.valueOf(editScale.getText().toString());
        if (scale.compareTo(0) <= 0 || Integer.valueOf(water.getLastScale()).compareTo(scale) > 0) {
            showTip("请填写正确的本期指数", QMUITipDialog.Builder.ICON_TYPE_FAIL);
            return;
        }
        try {
            long now = new Date().getTime();
            if (StringUtils.getLastDayOfMonth(water.getLastTime()).getTime() <= now) {
                map.put("accountId", water.getId());
                map.put("scale", String.valueOf(scale));
                if (choiceBack == null) {
                    map.put("feedback", "");
                } else {
                    map.put("feedback", String.valueOf(choiceBack));
                }

                map.put("latitude", mLat);
                map.put("longitude", mLng);
                MyConfirrmDialog myConfirrmDialog = MyConfirrmDialog.getInstance("111", "222");
                myConfirrmDialog.show(getSupportFragmentManager(), "dialog");
                myConfirrmDialog.setOnClick(new MyConfirrmDialog.onClick() {
                    @Override
                    public void onClickConfirm(String usedWater, String waterFee) {
                        WaterTask watertask = uploadWaterData(scale);
                        temp = water;
                        watertask.execute(map);
                    }
                });
            } else {
                showTip("当月该用户已抄表", QMUITipDialog.Builder.ICON_TYPE_FAIL);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    /**
     * 地理定位
     */
    private void initLocation() {
        LocationClient locationClient = LocationUtil.onCreate(this, new BDAbstractLocationListener() {
            @Override
            public void onReceiveLocation(BDLocation bdLocation) {
                if (CommonUtil.checkPermission(WaterActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION}, 2)) {
                    if (bdLocation.getLocType() == 62 || bdLocation.getLocType() == 63 || bdLocation.getLocType() == 67
                            || (bdLocation.getLocType() > 161 && bdLocation.getLocType() < 168)
                    ) {
                        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                        startActivityForResult(intent, 2);
                        return;
                    }
                } else {
                    return;
                }
                Double latitude = bdLocation.getLatitude();
                Double longitude = bdLocation.getLongitude();
                mLat = latitude.toString();
                mLng = longitude.toString();
                if (isClickUpload) {
                    upload();
                }
            }
        });
        locationClient.start();
    }

    /**
     * 提交数据上传
     *
     * @param scale
     * @return
     */
    private WaterTask uploadWaterData(final Integer scale) {
        return new WaterTask(HttpUtil.WATER_POST, WaterActivity.this, new BaseTask.SuccessCallback() {
            @Override
            public void excute(final JSONObject result) {
                showTip("抄表成功", QMUITipDialog.Builder.ICON_TYPE_SUCCESS);
                /*new QMUIDialog.MessageDialogBuilder(WaterActivity.this)
                        .setTitle("抄表成功")
                        .setMessage("确定打印票据吗？")
                        .addAction("取消", new QMUIDialogAction.ActionListener() {
                            @Override
                            public void onClick(QMUIDialog dialog, int index) {
                                dialog.dismiss();
                            }
                        })
                        .addAction("确定", new QMUIDialogAction.ActionListener() {
                            @Override
                            public void onClick(QMUIDialog dialog, int index) {
                                JSONObject account = result.optJSONObject("account");
                                dialog.dismiss();
                                PrintWater printWater = new PrintWater(temp.getId(), temp.getName(), temp.getArea(), temp.getLastScale()
                                        , temp.getLastTime(), sdf.format(new Date()), scale.toString(), account.optString("balance"),
                                        account.optString("arreage"), StrogeUtil.getStringFraomPs(WaterActivity.this, StrogeUtil.user, "loginName"));
                                Intent intent = new Intent(WaterActivity.this, PrinterSettingActivity.class);
                                intent.putExtra("entity", printWater);
                                startActivity(intent);
                            }
                        })
                        .create(com.qmuiteam.qmui.R.style.QMUI_Dialog).show();*/
                waterFlag = true;
                next();
            }
        }, bitmap);
    }


    private void next() {
        if (water == null) {
            Toast.makeText(this, "暂无抄表数据", Toast.LENGTH_SHORT).show();
            return;
        }
        baseTask = new BaseTask(HttpUtil.NEXT_WATER, WaterActivity.this, nextcallback);
        baseTask.setFailCallback(failCallback);
        map.put("accountId", String.valueOf(userId.getDetailText()));
        baseTask.execute(map);
    }

    /**
     * 修改手机号
     */
    private void editTel() {
        final QMUIDialog.EditTextDialogBuilder builder = new QMUIDialog.EditTextDialogBuilder(this);
        builder.setTitle("修改手机号")
                .setPlaceholder("在此输入手机号")
                .setDefaultText(water.getTel())
                .setInputType(InputType.TYPE_CLASS_NUMBER)
                .addAction("取消", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                    }
                })
                .addAction("确定", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(final QMUIDialog dialog, int index) {
                        final String text = builder.getEditText().getText().toString();
                        if (StringUtils.isEmpty(text)) {
                            Toast.makeText(WaterActivity.this, "请输入手机号", Toast.LENGTH_SHORT).show();
                        } else {
                            if (text.equals(water.getTel())) {
                                dialog.dismiss();
                                return;
                            }
                            Map<String, String> map = new HashMap<>();
                            map.put("tel", text);
                            map.put("accountId", water.getId());
                            new BaseTask(HttpUtil.EDIT_TEL, WaterActivity.this, new BaseTask.SuccessCallback() {
                                @Override
                                public void excute(JSONObject result) {
                                    dialog.dismiss();
                                    water.setTel(text);
                                    tel.setDetailText(text);
                                    showTip("修改成功", QMUITipDialog.Builder.ICON_TYPE_SUCCESS);
                                }
                            }).execute(map);
                        }
                    }
                })
                .create(com.qmuiteam.qmui.R.style.QMUI_Dialog).show();
    }

    /**
     * 修改置后
     */
    private void editPreSort() {
        final String presort = Constants.PRE_SORT.equals(water.getPresort()) ? "1" : "0";
        map.put("presort", presort);
        map.put("accountId", water.getId());
        new BaseTask(HttpUtil.PRE_SORT, WaterActivity.this, new BaseTask.SuccessCallback() {
            @Override
            public void excute(JSONObject result) {
                water.setPresort(presort);
                presortbtn.setText(presort.equals("1") ? "取消置后" : "置后");
                showTip("修改成功", QMUITipDialog.Builder.ICON_TYPE_SUCCESS);
            }
        }).execute(map);
    }


    /**
     * 修改排序
     */
    private void editSort() {
        final QMUIDialog.EditTextDialogBuilder builder = new QMUIDialog.EditTextDialogBuilder(this);
        builder.setTitle("修改排序号")
                .setPlaceholder("在此输入排序号")
                .setDefaultText(water.getSort())
                .setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL)
                .addAction("取消", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                    }
                })
                .addAction("确定", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(final QMUIDialog dialog, int index) {
                        final String text = builder.getEditText().getText().toString();
                        if (StringUtils.isEmpty(text)) {
                            Toast.makeText(WaterActivity.this, "请输入排序号", Toast.LENGTH_SHORT).show();
                        } else {
                            if (text.equals(water.getSort())) {
                                dialog.dismiss();
                                return;
                            }
                            Map<String, String> map = new HashMap<>();
                            map.put("sort", text);
                            map.put("accountId", water.getId());
                            new BaseTask(HttpUtil.EDIT_SORT, WaterActivity.this, new BaseTask.SuccessCallback() {
                                @Override
                                public void excute(JSONObject result) {
                                    dialog.dismiss();
                                    water.setSort(text);
                                    sort.setDetailText(text);
                                    showTip("修改成功", QMUITipDialog.Builder.ICON_TYPE_SUCCESS);
                                }
                            }).execute(map);
                        }
                    }
                })
                .create(com.qmuiteam.qmui.R.style.QMUI_Dialog).show();
    }

    private QMUITipDialog tipDialog;
    private Handler handler = new Handler();

    private void showTip(String title, int icon) {
        tipDialog = new QMUITipDialog.Builder(WaterActivity.this)
                .setIconType(icon)
                .setTipWord(title)
                .create();
        tipDialog.show();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                tipDialog.dismiss();
            }
        }, 1000);
    }


    BaseTask.SuccessCallback nextcallback = new BaseTask.SuccessCallback() {
        @Override
        public void excute(JSONObject result) {
            JSONObject account = result.optJSONObject("account");
            if (waterFlag && account == null) {
                qe_water_add.show("没发现需抄表用户", null);
                qg_water_add_list.setVisibility(View.GONE);
                return;
            } else {
                qg_water_add_list.setVisibility(View.VISIBLE);
                qe_water_add.hide();
            }
            if (account == null) {
                if (stepFlag) {
                    Toast.makeText(WaterActivity.this, "上一份不存在", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(WaterActivity.this, "下一份不存在", Toast.LENGTH_SHORT).show();
                }
                return;
            }
            if (account != null) {
                water = new Water(
                        account.optString("id"),
                        account.optString("name"),
                        account.optString("area"),
                        account.optString("tel"),
                        account.optString("sort"),
                        account.optString("preSort"),
                        account.optString("lastScale"),
                        account.optString("waterTime")
                );
                water.setCheck(result.optInt("check"));
                setAccount(water);
            }
        }
    };


    BaseTask.SuccessCallback callback = new BaseTask.SuccessCallback() {

        @Override
        public void excute(JSONObject result) {
            JSONObject account = result.optJSONObject("account");
            JSONArray feedback = result.optJSONArray("feedback");
            if (account == null) {
                qe_water_add.show("没发现需抄表用户", null);
                qg_water_add_list.setVisibility(View.GONE);
            } else {
                qg_water_add_list.setVisibility(View.VISIBLE);
                qe_water_add.hide();
            }
            if (account != null) {
                water = new Water(
                        account.optString("id"),
                        account.optString("name"),
                        account.optString("area"),
                        account.optString("tel"),
                        account.optString("sort"),
                        account.optString("preSort"),
                        account.optString("lastScale"),
                        account.optString("waterTime")
                );
                water.setCheck(result.optInt("check"));
                if (feedback != null) {
                    feedBackArray = new String[feedback.length() + 1];
                    feedBackArray[0] = "不选择";
                    for (int i = 0; i < feedback.length(); i++) {
                        JSONObject temp = feedback.optJSONObject(i);
                        feedBacks.put(temp.optString("dictLabel"), temp.optInt("dictValue"));
                        feedBackArray[i + 1] = temp.optString("dictLabel");
                    }
                }
                setAccount(water);
            }
        }
    };


    BaseTask.FailCallback failCallback = new BaseTask.FailCallback() {
        @Override
        public void excute(String result) {
            qe_water_add.show(false, "查询结果", result, null, null);
        }
    };


}
